package com.dataStructures.search;

/**
 * 二分查找非递归
 */
public class BinarySearchNoRecursion {
	public static void main(String[] args) {
		int[] arr = {1, 3, 5, 7, 23, 34, 56};
		int index = binarySearch(arr, 34);
		System.out.println(index);
	}

	/**
	 * 二分查找的非递归实现
	 *
	 * @param arr    数组
	 * @param target 目标值
	 * @return 目标值在数组的下标
	 */
	public static int binarySearch(int[] arr, int target) {
		int left = 0;
		int right = arr.length - 1;
		while (left <= right) {
			int mid = (left + right) / 2;
			if (arr[mid] == target) {
				return mid;
			} else if (arr[mid] > target) {
				right = mid - 1;
			} else {
				left = mid + 1;
			}
		}
		return -1;
	}
}
